iT邦幫忙

2023 iThome 鐵人賽

DAY 22
0
自我挑戰組

chatGPT 帶你從零開始寫 websocket 連線遊戲系列 第 22

D22 來開房間吧 websocket 建立/加入房間以及開始遊戲

  • 分享至 

  • xImage
  •  

在 D8 我們談到房間管理的邏輯,但是跟 websocket 關聯的部分還沒有講清楚,所以我們今天就實作這部分吧

import asyncio
import websockets
import json

# 存儲房間和玩家的資訊
rooms = {}
players = {}

# 定義 WebSocket 伺服器的處理邏輯
async def game_server(websocket, path):
    while True:
        try:
            message = await websocket.recv()
            if not message:
                break
            data = json.loads(message)
            action = data.get("action")
            payload = data.get("payload")
            if action:
                if action == "create_room":
                    # 創建房間
                    room_id = len(rooms) + 1
                    rooms[room_id] = [websocket]
                    response = {"message": f"Room created with ID {room_id}"}
                    await websocket.send(json.dumps(response))
                elif action == "join_room":
                    # 加入房間
                    room_id = payload.get("room_id")
                    if room_id in rooms and len(rooms[room_id]) < 2:
                        rooms[room_id].append(websocket)
                        response = {"message": f"Joined room {room_id}"}
                        await websocket.send(json.dumps(response))
                    else:
                        response = {"error": "Room is full or does not exist"}
                        await websocket.send(json.dumps(response))
                elif action == "start_game":
                    # 開始遊戲
                    room_id = payload.get("room_id")
                    if room_id in rooms and len(rooms[room_id]) == 2:
                        response = {"message": "Starting the game..."}
                        await websocket.send(json.dumps(response))
                        # 在這裡可以加入遊戲的邏輯
                    else:
                        response = {"error": "Invalid room or not enough players"}
                        await websocket.send(json.dumps(response))
        except websockets.ConnectionClosed:
            break

# 啟動 WebSocket 伺服器
start_server = websockets.serve(game_server, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Game Client</title>
</head>
<body>
    <h1>WebSocket Game</h1>
    <div id="messages"></div>
    <button onclick="sendMessage('create_room')">Create Room</button>
    <button onclick="joinRoom()">Join Room</button>
    <button onclick="startGame()">Start Game</button>
    
    <script>
        var ws;
        var messages = document.getElementById("messages");

        function showMessage(message) {
            var p = document.createElement("p");
            p.textContent = message;
            messages.appendChild(p);
        }

        function sendMessage(action, payload = {}) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                var message = JSON.stringify({ action: action, payload: payload });
                ws.send(message);
            } else {
                showMessage("WebSocket not connected.");
            }
        }

        function joinRoom() {
            var room_id = prompt("Enter room ID:");
            if (room_id) {
                sendMessage('join_room', { room_id: room_id });
            }
        }

        function startGame() {
            var room_id = prompt("Enter room ID to start the game:");
            if (room_id) {
                sendMessage('start_game', { room_id: room_id });
            }
        }

        ws = new WebSocket("ws://localhost:8765");

        ws.onmessage = function(event) {
            var data = JSON.parse(event.data);
            showMessage(data.message || data.error);
        };
    </script>
</body>
</html>

解說

(待補)

完整問答


上一篇
D21 產出基礎遊戲邏輯
下一篇
D23 打磨遊戲程式碼
系列文
chatGPT 帶你從零開始寫 websocket 連線遊戲31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言